<?php

use app\modules\Admin\models\scoregoodsModel;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Relations\HasOne;
use app\modules\Admin\service\Scoreshop as ScoreshopService;
#[积分商城管理]
class ScoreshopController extends AcommonController
{
    public function init() {
        $this->model = (new scoregoodsModel());
        $this->table = 'score_goods';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[积分商城商品列表]
    public function indexAction($returnData = false)
    {
        if($this->isPost()) {
            $query = $this->model->groupby('goods_id')->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            });
            $postData = $this->postData;
            $keyword = isset($postData['scoreshopKeywords']) && !empty($postData['scoreshopKeywords'])?$postData['scoreshopKeywords']:'';
            if($keyword){
                $goods_id_arr = goodsModel::query()->where('id', $keyword)->orWhere('title', 'like', "%{$keyword}%")->pluck('id')->toArray();
                $query = $query->whereIn('goods_id', $goods_id_arr);
            }
            unset($postData);
            $countQuery = clone $query;
            $total = $countQuery->select('id')->get()->count();
            $sort = $this->get('sort', 'created_at');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy($sort, $order)->orderBy($this->primaryKey, 'DESC');
            $page = $this->get('page');

            if (!empty($page)) {
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
            }
            $query =  $query->with([
                'goods' => function (HasOne $query) {
                    $query->select(['id', 'image', 'title', 'is_sku']);
                }
            ])->withSum('score_sku', 'stock');
            $rows = $query->get();
            if(!empty($this->appends)){
                foreach ($this->appends as $append){
                    $rows = $rows->append($append);
                }
            }
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display( strtolower($this->controller) . '/index.html');
        }
    }

    #[新增积分商品]
    public function addAction()
    {
        if(!$this->isPost()){
            $this->_view->assign('dataset', json_encode((object)null));
            $this->_view->assign('category', $this->categoryTree()->toJson());
            $this->_view->display( strtolower($this->controller) . '/add.html');
        }
    }

    #[积分商品链接]
    public function linkAction()
    {
        $id = $this->get('id');
        $config = \Yaf_Registry::get('config');
        ret(0, '积分商品链接', $config->application->hostUrl . '/h5/#/pages/goods/detail?id='.$id.'&type=score');
    }

    #[保存积分商品]
    public function saveAction()
    {
        if(!$this->isPost()){
            ret(1, '非法提交');
        }
        if(isset($this->postData['params']) && is_array($this->postData['params'])){
            if(count($this->postData['params'])){
                $insert_data = [];
                $update_data = [];
                $delete_ids = [];
                $params = $this->postData['params'];
                foreach ($params as $key => $item){
                    switch ($item['score_option']){
                        case 'add':
                            if($item['score_in'] == 0 && $item['score_id'] == 0){
                                $insert_data[] = [
                                    'sku_price_id'=>$item['sku_goods_price_id'],
                                    'goods_id'=>$item['sku_goods_id'],
                                    'status'=>'up',
                                    'stock'=>$item['score_stock'],
                                    'sales'=>'0',
                                    'price'=>$item['score_price'],
                                    'score'=>$item['score_score'],
                                    'created_at' => timestamp(),
                                ];
                            }
                            break;
                        case 'edit':
                            if($item['score_in'] &&$item['score_id']){
                                $update_data[$item['score_id']] = [
                                    'status'=>'up',
                                    'stock'=>$item['score_stock'],
                                    'price'=>$item['score_price'],
                                    'score'=>$item['score_score'],
                                    'updated_at' => timestamp(),
                                    'deleted_at' => null,
                                ];
                            }
                            break;
                        case 'del':
                            if($item['score_in'] &&$item['score_id']){
                                $delete_ids[] = $item['score_id'];
                            }
                            break;
                    }
                }
                unset($key);
                unset($item);
                try{
                    DB::transaction(function () use ($insert_data, $update_data, $delete_ids) {
                        if(is_array($insert_data) && count($insert_data)){
                            scoregoodsModel::query()->insert($insert_data);
                        }
                        if(is_array($update_data) && count($update_data)){
                            foreach ($update_data as $upKey => $upData){
                                scoregoodsModel::query()->where('id', $upKey)->update($upData);
                            }
                            unset($upKey);
                            unset($upData);
                        }
                        if(is_array($delete_ids) && count($delete_ids)){
                            scoregoodsModel::query()->whereIn('id', $delete_ids)->update(['status' => 'down', 'updated_at' => timestamp()]);
                        }
                    });
                    ret(0, '恭喜，积分商品设置成功! ^_^');
                }catch (Exception $e){
                    ret(1, '抱歉，积分商品设置失败。');
                } finally {
                    unset($params);
                    unset($insert_data);
                    unset($update_data);
                    unset($delete_ids);
                }
            }
        }else{
            ret(1, '非法数据');
        }
    }

    #[删除积分商品]
    public function deleteAction()
    {
        if($this->isPost()) {
            $goods_id = $this->postData['goods_id'];
            if(!is_numeric($goods_id)){
                ret(2, '非法参数');
            }
            $this->model = $this->model->where('goods_id', $goods_id)->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            });
            if($this->model->exists()){
                if($this->model->update(['status' => 'down', 'deleted_at' => timestamp()])){
                    ret(0, '积分商城商品删除成功！');
                }else{
                    ret(1, '积分商城商品删除失败！');
                }
            }else{
                ret(3, '商品不存在或已删除');
            }
        }
    }

    #[递归商品目录]
    private function categoryTree(&$item = [])
    {
        $children = categoryModel::where('pid', $item['id'] ?? 0)->select('id', 'name as text')->orderBy('weigh', 'DESC')->orderBy('id', 'ASC')->get();
        if ($children->isNotEmpty()) {
            $item && $item->children = $children;
            foreach ($children as $v) {
                $v->name = htmlentities($v->name);
                $this->categoryTree($v);
            }
        }
        return $children;
    }

    #[获取商品列表]
    public function getgoodsAction()
    {
        if($this->isPost()) {
            $query = new goodsModel();
            $query = $query->where('status', 'up')->where('is_package', 0)->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            });
            $keywords = $this->get('keywords');
            if (!empty($keywords)) {
                $query = $query->Where(function ($orwQuery) use($keywords){
                    $orwQuery->where('title', 'like',  "%{$keywords}%")
                    ->orWhere('id', $keywords);
                });
            }
            if(!empty($this->postData['category_id'])){
                $query = $query->whereRaw("FIND_IN_SET(?, category_ids)", $this->postData['category_id']);
            }
            $total = $query->count();
            $sort = $this->get('sort', 'created_at');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy($sort, $order)->orderBy('id', 'DESC');
            $page = $this->get('page');
            if (!empty($page)) {
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
            }
            $rows = $query->select(['id', 'image', 'title', 'is_sku', 'price'])->get();
            $goodsStock = goodsskupriceModel::select(DB::raw('sum(stock) as allstock'), 'goods_id')->groupBy('goods_id')->pluck('allstock', 'goods_id');
            foreach ($rows as $row){
                $row->stock = $goodsStock[$row->id];
            }
            json(['total' => $total, 'rows' => $rows]);
        }
    }

    #[获取商品SKU]
    public function getgoodsskupriceAction()
    {
        $goods_id = $this->get('goods_id');
        if(empty($goods_id)){
            ret(1, '没有选择商品！');
        }
        if(goodsModel::where([['id', '=',$goods_id],['status', '=', 'up']])->doesntExist()){
            ret(1, '商品不存在！');
        }
        $mode = $this->get('mode')??'';
        if(!empty($mode)){
            if ($mode == 'check'){
                if(scoregoodsModel::query()->where('goods_id', $goods_id)->where(function ($query){
                    $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
                })->exists()){
                    ret(1, '商品已经是积分商品！');
                }else{
                    ret(0, 'success');
                }
            }elseif ($mode == 'getsku'){
                $goods_info = goodsModel::query()->where([['id', '=',$goods_id]])->where(function ($query){
                    $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
                })->select(['id', 'image', 'title'])->first()->makeHidden(['dispatch_type_arr', 'parent_category_id'])->toArray();
                $goodsskuprice = goodsskupriceModel::query()->where([
                    ['goods_sku_price.goods_id', '=', $goods_id]
                ])->leftjoin($this->table, 'goods_sku_price.id', '=', 'sku_price_id')
                    ->select([
                        'goods_sku_price.id as sku_goods_price_id',
                        'goods_sku_price.goods_id as sku_goods_id',
                        'goods_sku_price.goods_sku_text as sku_text',
                        'goods_sku_price.stock as sku_goods_stock',
                        'goods_sku_price.price as sku_price',
                        'goods_sku_price.goods_sku_ids',
                        'score_goods.id as score_id',
                        'score_goods.status as score_status',
                        'score_goods.stock as score_stock',
                        'score_goods.price as score_price',
                        'score_goods.score as score_score',
                        'score_goods.sales as score_sales',
                        'score_goods.deleted_at as score_deleted_at',
                    ])->get();
                if($goodsskuprice){
                    foreach ($goodsskuprice as &$item){
                        if(is_array($item->goods_sku_id_arr) && count($item->goods_sku_id_arr)){
                            $item->goods_sku = ScoreshopService::formatGoodsSku($item->goods_sku_id_arr, $item->sku_text);
                            $item->makeHidden(['goods_sku_ids', 'goods_sku_id_arr', 'sku_text']);
                        }
                        //格式化积分商品中的为NULL的项目；
                        $item->score_id = $item->score_id?:0;
                        $item->score_sales = $item->score_sales?:0;
                        $item->score_stock = $item->score_stock?:0;
                        $item->score_price = $item->score_price?:0;
                        $item->score_score = $item->score_score?:0;
                        //设置操作项
                        $item->score_in = 0;
                        $item->score_option = 'normal';
                        if(!empty($item->score_id)){
                            $item->score_in = 1;
                            $item->score_option = 'edit';
                            if($item->score_status == 'down'){
                                $item->score_option = 'drop';
                            }
                        }
                    }
                }
                $this->_view->assign('is_edit', $this->get('ise')??0);
                $this->_view->assign('goods_info', json_encode($goods_info, JSON_UNESCAPED_UNICODE));
                $this->_view->assign('sku_info', $goodsskuprice->toJson());
                $this->_view->display( strtolower($this->controller) . '/edit.html');
            }else{
                ret(2, '参数出错！');
            }
        }
    }
}